﻿// -----------------------------------------------------------------------
// <copyright file="BusinessHelper.cs" company="AGR">
// TODO: Update copyright text.
// </copyright>
// -----------------------------------------------------------------------

namespace AGR.Services
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Text.RegularExpressions;

    /// <summary>
    /// TODO: Update summary.
    /// </summary>
    public static class BusinessHelper
    {
        private const string MatchEmailPattern =
                  @"^(([\w-]+\.)+[\w-]+|([a-zA-Z]{1}|[\w-]{2,}))@"
           + @"((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?
				[0-9]{1,2}|25[0-5]|2[0-4][0-9])\."
           + @"([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?
				[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|"
           + @"([a-zA-Z]+[\w-]+\.)+[a-zA-Z]{2,4})$";

        public static bool ValidateEmail(string email)
        {
            try
            {
                if (!string.IsNullOrEmpty(email))
                {
                    return Regex.IsMatch(email, MatchEmailPattern);
                }
                else
                {
                    return false;
                }
            }
            catch (ArgumentException)
            {
                return false;
            }
        }

        public static Nullable<DateTime> GetDateTime(string dateString)
        {
            Nullable<DateTime> hireDate = null;

            try
            {
                hireDate = DateTime.Parse(dateString);
            }
            catch (Exception)
            {
                return null;
            }

            return hireDate; 
        }

        public static int GetWeeks(DateTime? startDate, DateTime? endDate)
        {
            TimeSpan t = endDate.Value - startDate.Value;
            int days;

            if (t.Days < 7)
            {
                if (startDate.Value.DayOfWeek > endDate.Value.DayOfWeek)
                {
                    // It is accross the week 
                    return 1;
                }
                else
                {
                    // same week
                    return 0;
                }
            }
            else
            {
                days = t.Days - 7 + (int)startDate.Value.DayOfWeek;
                int i = 0;
                int k = 0;

                for (i = 1; k < days; i++)
                {
                    k += 7;
                }

                if (i > 1 && endDate.Value.DayOfWeek != DayOfWeek.Sunday)
                {
                    i -= 1;
                }

                return i;
            }
        }
    }
}
